const Http = require('./http.js');
const Store = require('electron-store');
const getUserDataPath = require('./getUserDataPath');
const log = require('electron-log');
const configManager = require('./config');
const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const http = new Http();

const store = new Store({
    name: 'sync',
    cwd: getUserDataPath(),
});
const user = store.get('user');
class syncUpFileCheck {
    constructor() {
        this.fileLists = [];
        this.folderPath = configManager.getLocal().folderPath;
    }
    getAllList() {
        return new Promise(async(resolve) => {
            const downProject = store.get('downProject', {});
            const projects = Object.keys(downProject).map((td) => {
                return downProject[td].busId;
            });
            const data = {
                mainId: store.get('mainId'),
                nodeTypes: [100, 101],
                busIds: projects,
            };
            const res = await http.request(
                'POST',
                '/bimfile/doc-sync/queryLocalList',
                data
            );
            if(res.success){
                this.fileLists = res.data;
                resolve(res.data);

            }else{
                log.info('failed')
                log.info({
                    res
                })
                resolve([]);
            }
        });
    }

    checkAddList(tempAddList, tempChangeList) {
        log.info(tempAddList);
        let list = tempAddList.concat(tempChangeList);
        const resultAdd = _.pullAllWith(list, this.fileLists, (x, y) => {
            const local = path.join(this.folderPath, y.projectName);
            const localPath = y.dirPath ? path.join(local, y.dirPath) : local;
            return x.filePath == path.join(localPath, y.nodeName);
        });
        return resultAdd;
    }

    checkChangeList(tempChangeList) {
        log.info({ tempChangeList });
        const obj = {};
        this.fileLists.map((y) => {
            const local = path.join(this.folderPath, y.projectName);
            const localPath = y.dirPath ? path.join(local, y.dirPath) : local;
            const filePath = path.join(localPath, y.nodeName);
            obj[filePath] = {
                nodeId: y.nodeId,
                filePath: filePath,
            };
        });
        return tempChangeList
            .filter((td) =>  obj[td.filePath] && obj[td.filePath].filePath)
            .map((td) => {
                return {
                    filePath: td.filePath,
                    nodeId: obj[td.filePath].nodeId,
                };
            });
    }

    getProjectId(filePath) {
            let projectname = path.relative(
                configManager.getLocal().folderPath,
                filePath
            );

            let names = path.dirname(projectname);

            let logs = names.replace(/\\/g, '/');

            let name = logs.split('/')[0];
            const projectObj = store.get('downProject', {});
            if (projectObj[name]) {
                return projectObj[name].busId;
            } else {
                return null;
            }
        }
        // 创建任务，并发起上传
    async createUploadTask(list, fileTransferHelper, port) {
        // 過濾已經刪除的文件
        const newLists = list.filter((file) => fs.existsSync(file.filePath));
        const newListsUniq = _.uniqBy(newLists,'filePath')
        const params = {
            mid: user.mid,
            mainId: store.get('mainId'),
            syncType: 2,
            coId: user.coId,
            uploadOrUpdateList: newListsUniq.map((file) => {
                return {
                    nodeName: path.basename(file.filePath),
                    nodeId: file.nodeId,
                    dirPath: file.filePath,
                    busId: this.getProjectId(file.filePath),
                };
            }),
        };

        log.info({ createUploadTask: params });
        log.info({ uploadOrUpdateList: params.uploadOrUpdateList });

        const res = await http.request(
            'POST',
            '/bimfile/doc-sync/newSyncTask',
            params
        );
        if (res.success) {
            log.info({ res: res.data });
            // 先创建目录
            fileTransferHelper.createUploadTask({
                items: [{
                    taskId: res.data.taskId,
                    coId: user.coId,
                }, ],
            });
        } else {
            port.postMessage({
                type: 'file:upload:start',
                loading: false,
            });
            log.info('创建上传任务失败');

            log.info(res.errMessage);
        }
    }

    checkFileType(path) {
        return new Promise((resolve) => {
            fs.stat(path, (err, stats) => {
                if (err) {
                    console.error(err);
                    return;
                }

                if (stats.isFile()) {
                    resolve(true);
                } else if (stats.isDirectory()) {
                    resolve(false);
                }
            });
        });
    }
    checkUnlinkList(tempUnlinkList) {
        log.info({ tempUnlinkList });
        let obj = {};
        this.fileLists.map((y) => {
            const local = path.join(this.folderPath, y.projectName);
            const localPath = y.dirPath ? path.join(local, y.dirPath) : local;
            const filePath = path.join(localPath, y.nodeName);
            obj[filePath] = {
                nodeId: y.nodeId,
                filePath: filePath,
                nodeName: y.nodeName,
            };
        });
        return tempUnlinkList
            .filter((td) => obj[td.filePath] && obj[td.filePath].filePath)
            .map((td) => {
                return {
                    filePath: td.filePath,
                    nodeType: td.nodeType,
                    nodeId: obj[td.filePath].nodeId,
                    nodeName: obj[td.filePath].nodeName,
                };
            });
    }

    deleteFileStatus(list, port) {
        return new Promise(async(resolve) => {
            let data = {
                mainId: store.get('mainId'),
                mid: user.mid,
                deleteInfos: list,
            };

            const res = await http.request(
                'POST',
                '/bimfile/doc-sync/deleteLocalTask',
                data
            );
            if (res.success) {
                port.postMessage({
                    type: 'file:delete:refresh',
                    loading: false,
                });
                log.info('删除成功');
                resolve(true);
            } else {
                log.info('删除失敗' + res.errMessage);
                resolve(false);
            }
        });
    }

    checkStartService(list) {
        return new Promise(async(resolve, reject) => {
            console.log('本地检测的list');

            console.log(list);
            let filesLine = await this.getAllList();

            let filesObj = {};
            let pathArray = [];
            let resultDelete = [];
            filesLine.map((y) => {
                const local = path.join(this.folderPath, y.projectName);
                const localPath = y.dirPath ? path.join(local, y.dirPath) : local;
                const filePath = path.join(localPath, y.nodeName);
                pathArray.push(filePath);
                if (list.indexOf(filePath) == -1) {
                    resultDelete.push({
                        nodeId: y.nodeId,
                        filePath: filePath,
                        nodeName: y.nodeName,
                        nodeType: y.nodeType,
                    });
                }
                filesObj[filePath] = {
                    nodeId: y.nodeId,
                    filePath: filePath,
                    nodeName: y.nodeName,
                    nodeType: y.nodeType,
                };
            });

            // 获取和本地文件库匹配不上的文件，排除没有项目id的文件
            const resultAdd = _.pullAllWith(list, pathArray, (x, y) => {
                return x == y || x == this.folderPath||x.lastIndexOf('.tmp') != -1 ||x.lastIndexOf('.download') != -1 || x.lastIndexOf('~$') != -1
            });

            let resultAddNofolder = [];
            for (let i = 0; i < resultAdd.length; i++) {
                const type = await this.checkFileType(resultAdd[i]);
                if (type && this.getProjectId(resultAdd[i])) {
                    resultAddNofolder.push({
                        filePath: resultAdd[i]
                    });
                }
            }
            log.info('检测关闭时新增');
            log.info(resultAddNofolder);

            log.info('检测关闭时删除');
            log.info(resultDelete);

            resolve({
                addFiles: resultAddNofolder,
                deleteFiles: resultDelete,
            });
        });
    }
}
module.exports = syncUpFileCheck;
